package jp.co.cos.ittrick.channel.controller.client;

import jp.co.cos.ittrick.channel.meta.ChannelModelMeta;
import jp.co.cos.ittrick.channel.model.ChannelModel;
import jp.co.cos.ittrick.channel.service.ChannelService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Key;

public class InsertChannelController extends Controller {

    private ChannelService service;

    public InsertChannelController() {
        service = new ChannelService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String channel = asString("channel");
        String name = asString("name");
        String index = asString("index");

        // Modelの設定
        ChannelModel model = new ChannelModel();
        model.setName(name);
        model.setIndex(Integer.valueOf(index));

        // Insert
        Key key = service.insert(channel, model);

        // 再取得して返す
        model = service.getChannelByKey(key.getName());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter().println(ChannelModelMeta.get().modelToJson(model));
        response.flushBuffer();

        return null;
    }
}
